import React, { useEffect, useRef, useState } from 'react';
import './index.css';
import Photolibrary from './component/Photolbrary';
import { text } from 'stream/consumers';
import useFileStore from '@/store/files';
import { paintBoard } from '@/core/paintBoard';
import useBoardStore from '@/store/board';
import { ActionMode } from '@/constants';
import DownloadImage from '@/components/boardOperation/downloadImage';
import UploadImage from '@/components/boardOperation/uploadImage';
import { message } from 'antd';
import { ImageElement } from '@/core/element/image';

const panelStyle: React.CSSProperties = {
    position: 'fixed',
    top: 0,
    right: 0,
    width: '340px',
    height: '100%',
    background: '#fff',
    boxShadow: '-2px 0 8px rgba(0,0,0,0.15)',
    transform: 'translateX(100%)',
    transition: 'transform 0.3s ease',
    zIndex: 1000,
    padding: '5px',
};

const panelOpenStyle: React.CSSProperties = {
    ...panelStyle,
    transform: 'translateX(0)',
};
const ControlPanel: React.FC = () => {
    const [open, setOpen] = useState(false);
    const {
        files,
        currentId,
        updateCurrentFile,
        updateTitle,
        addFile,
        saveJSON,
        uploadFile,
        getCurrentFile
    } = useFileStore()
    const { updateMode } = useBoardStore()
    const [showUploadFail, updateShowUploadFail] = useState(false) // upload file toast
    const [downloadImageURL, setDownloadImageURL] = useState('')
    const [showDownloadModal, setShowDownloadModal] = useState(false)
    const [uploadImageURL, setUploadImageURL] = useState('')
    const [parentUrl, setParentUrl] = useState('')
    const [showFile, updateShowFile] = useState(false) // show file list draw
    const [showUploadModal, setShowUploadModal] = useState(false)
    const parentUrlRef = useRef('');
    useEffect(() => {
        // 这里相当于页面onload
        window.addEventListener('message', receiveMessage, false)
    }, []); // 空依赖数组表示只在组件挂载时执行一次
    // update file
    const receiveMessage = async (event: any) => {
        if (event.data.type == 'url') {
            parentUrlRef.current = event.data.data.url
            postMessage('clearInterval', true)
        } else if (event.data.type == 'importData' && event.data.data) {
            importData(event.data.data)
        } else if (event.data.type == 'importImg') {
            importImg(event.data.data)
        }
    }
    // 图片导入
    const importImg = (dataStr: string) => {
        const image = new ImageElement();
        image.addImage(dataStr);
        message.success('导入成功!')
    }
    // json数据导入
    const importData = (dataStr: string) => {
        try {
            const data = JSON.parse(dataStr)
            console.log('import data:', data)
            if (data && data.boardData) {
                uploadFile(new File([dataStr], 'import.json', { type: 'application/json' })).then((res: boolean) => {
                    if (res) {
                        paintBoard.initCanvasStorage()
                        updateMode(ActionMode.DRAW)
                        message.success('导入成功!')
                    } else {
                        message.error('导入失败!请检查文件内容是否正确')
                    }
                })
            } else {
                message.error('导入失败!请检查文件内容是否正确')
            }
        } catch (error) {
            message.error('导入失败!请检查文件内容是否正确')
            console.error('Failed to parse JSON:', error);
        }
    }
    //向父级窗口传数据
    const postMessage = (type: string, data: any) => {
        window.parent.postMessage(
            {
                type: type,
                data: data
            },
            parentUrlRef.current
        )
    }
    const handleUploadFile = (file?: File) => {
        console.log('upload file:', file)
        uploadFile(file).then((res: boolean) => {
            if (res) {
                paintBoard.initCanvasStorage()
                updateMode(ActionMode.DRAW)
            } else {
                updateShowUploadFail(true)
                setTimeout(() => {
                    updateShowUploadFail(false)
                }, 1500)
            }
        })
    }
    // 保存图片
    const saveImage = () => {
        if (paintBoard.canvas) {
            const url = paintBoard.canvas.toDataURL()
            setDownloadImageURL(url)
            setShowDownloadModal(true)
        }
    }
    // 导出为base64
    const exportAsPngbase64 = () => {
        if (paintBoard.canvas) {
            const url = paintBoard.canvas.toDataURL()
            postMessage('exporbase64Images', url)
            message.success('导出成功!')
        }
    }
    // 导出为json
    const exportAsExportCanvasJson = () => {
        if (paintBoard.canvas) {
            const json = getCurrentFile()[0]
            console.log('export canvas json:', json)
             const dataStr = JSON.stringify(json, null, 2)
            postMessage('exportData', dataStr)
            message.success('导出成功!')
        }
    }
    // 导出全部
    const exportALLdata = () => {
        if (paintBoard.canvas) {
            let data = {
                base64Images: '',
                JSONData: ''
            }
            const url = paintBoard.canvas.toDataURL()
            data.base64Images = url
            const json = getCurrentFile()[0]
            data.JSONData = JSON.stringify(json)
            console.log('export all data:', data)
            postMessage('exportAll', data)
            message.success('导出成功!')
        }
    }

    return (
        <>
            <div className="control-panel">
                <div className='action-buttons'>
                    <div className="h1">通用功能</div>
                    <div className='btn-item' onClick={() => setOpen(true)} >打开图库</div>
                    <div className='btn-item' onClick={saveJSON}>下载可编辑文件</div>
                    <label htmlFor="file-upload" className="btn-item">
                        导入可编辑文件
                        <input
                            type="file"
                            accept="application/json"
                            id="file-upload"
                            className="hidden"
                            onChange={(e) => handleUploadFile(e.target.files?.[0])}
                        />
                    </label>
                    <div className='btn-item' onClick={saveImage}>下载png</div>
                    <div className="h1">其他功能</div>
                    <div className='btn-item' onClick={exportAsPngbase64}>导出base64</div>
                    <div className='btn-item' onClick={exportAsExportCanvasJson}>导出画布数据</div>
                    <div className='btn-item' onClick={exportALLdata}>导出全部</div>
                </div>
                <div style={open ? panelOpenStyle : panelStyle}>
                    <button
                        style={{
                            position: 'absolute',
                            top: 16,
                            right: 16,
                            background: 'none',
                            border: 'none',
                            fontSize: 20,
                            cursor: 'pointer',
                        }}
                        onClick={() => setOpen(false)}
                    >
                        ×
                    </button>
                    <h2 style={{ textAlign: 'center' }}>点击拖动添加到画布</h2>
                    {/* 在这里添加照片内容 */}
                    <Photolibrary />

                </div>
            </div>
            {showDownloadModal && downloadImageURL && (
                <DownloadImage
                    url={downloadImageURL}
                    showModal={showDownloadModal}
                    setShowModal={setShowDownloadModal}
                />
            )}
            <UploadImage
                url={uploadImageURL}
                showModal={showUploadModal}
                setShowModal={setShowUploadModal}
            />
        </>
    );
};

export default ControlPanel;